import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'dva/router';
import { Breadcrumb } from 'antd';
import styles from './index.less';

export default class Brdm extends React.Component {
  static contextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  };

  // 组装面包屑数据
  getBreadcrumbData = () => {
    const { location, breadcrumbNameMap } = this.context;
    const arr = Object.keys(breadcrumbNameMap);
    const filterArr = arr.filter(item =>
      location.pathname.includes(item) && (item !== '/') && (item.split('/').length > 2) && breadcrumbNameMap[item].component
    );
    const breadcrumbData = [];

    filterArr.forEach(item => {
      breadcrumbData.push({
        path: item,
        ...breadcrumbNameMap[item],
      });
    });

    return breadcrumbData;
  };

  // 渲染子面包屑
  renderBreadcrumbItem = () => {
    const breadcrumbData = this.getBreadcrumbData();
    const { length } = breadcrumbData;

    if (length > 0) {
      return breadcrumbData.map((item, index) =>{
        if (index === (length -1)) {
          return  <Breadcrumb.Item key={item.path}>{item.name}</Breadcrumb.Item>
        }

        return <Breadcrumb.Item key={item.path}><Link to={item.path}>{item.name}</Link></Breadcrumb.Item>
      });
    }
  };

  render() {
    this.getBreadcrumbData();
    return (
      <Breadcrumb className={styles.breadcrumb}>
        <Breadcrumb.Item><Link to="/welcome">首页</Link></Breadcrumb.Item>
        {this.renderBreadcrumbItem()}
      </Breadcrumb>
    );
  }
}
